<template>
  <el-form-item label="电子版附件">
    <el-upload
      action="http://120.78.68.201:3000/uploadfile"
      :on-preview="handlePreview"
      :before-remove="beforeRemove"
      :on-success="handSuccess"
      :on-error="handError"
      :limit="6"
      :on-exceed="handleExceed"
      multiple
      style="width:80%"
      :data="userInfo"
      :headers="{ Authorization: this.token }"
      :file-list="oldFileData"
    >
      <el-button size="small" type="primary">点击上传</el-button>
      <div class="tip" slot="tip">
        支持至多 <span style="color:#F56C6C">6</span> 个文件上传，每个文件不超过 <span style="color:#F56C6C">5M</span>。<br />
        使用该功能时确保浏览器处于“极速模式”，IE版本需IE10以上。<br />
        如遇到上传失败或其他错误，请检查文件大小，或重新登录、更换浏览器使用。
      </div>
    </el-upload>
  </el-form-item>
</template>
<script>
let BaaS = window.BaaS;
import $ from "jquery";
import { Message } from "element-ui";
export default {
  props: ["createTime", "oldFileData", "token"],
  data() {
    return {
      userInfo: {
        id: "id_" + BaaS.storage.get("uid"),
        name: this.createTime,
      },
    };
  },
  watch: {},
  computed: {},
  methods: {
    handError(err, file) {
      let { message } = err;
      if (JSON.parse(message).message == "文件已存在") {
        this.$message.error(`文件 ${file.name} 已存在`);
      } else {
        this.$message.error(`文件 ${file.name} 上传失败`);
      }
    },
    // 下载文件
    handlePreview(file) {
      this.$confirm(`下载文件 ${file.name} ？`, "下载...", {
        confirmButtonText: "下载",
        cancelButtonText: "取消",
        type: "info",
      })
        .then(() => {
          this.downloadFile(
            file.name,
            `http://120.78.68.201:3000/download/${this.userInfo.id}/${this.userInfo.name}/${file.name}`,
            this.token
          );
        })
        .catch((err) => err);
    },
    downloadFile(filename, fileUrl, token) {
      const xhr = new XMLHttpRequest();
      const url = fileUrl;
      xhr.open("get", url, true);
      xhr.setRequestHeader("Authorization", token); // 给后端发送请求头
      xhr.responseType = "blob";
      xhr.onload = function() {
        if (this.status === 200) {
          const blob = this.response;
          const urlObject = window.URL || window.webkitURL || window;
          const export_blob = new Blob([blob]);
          const a = document.createElementNS("http://www.w3.org/1999/xhtml", "a"); // 利用a标签特性下载
          const url = urlObject.createObjectURL(export_blob);
          a.href = url;
          a.download = filename;
          a.click();
        }
      };
      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
          if (xhr.status !== 200) {
            Message.error({ message: "下载失败" });
          }
        }
      };
      xhr.send();
    },
    // 超过文件数量限制
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 6 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    beforeRemove(file) {
      return this.$confirm(`确定删除 ${file.name}？`).then(() => {
        return $.ajax(`http://120.78.68.201:3000/delete/${this.userInfo.id}/${this.userInfo.name}/${file.name}`, {
          headers: {
            Authorization: this.token,
          },
        })
          .done(() => {
            this.$emit("deleteFile", file.name);
            this.$message.warning("删除成功！");
          })
          .fail(() => {
            this.$message.warning("删除失败！");
          });
      });
    },
    // 上传成功
    handSuccess(res) {
      if (res.message == "success") {
        this.$message.success("文件上传成功！");
        this.$emit("filePath", {
          name: res.data.path,
          status: "success",
          url: `/${res.data.path}`,
        });
      }
    },
  },
  mounted() {},
};
</script>
<style scoped>
.tip {
  font-size: 13px;
  color: #606266;
  margin-top: 7px;
}
</style>
